package com.example.demo.chacheable;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.StringUtils;
/**
 * @Author jsc
 * @Description //TODO
 * @Date 2020/1/15
 **/
@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisConfiguration {
  @Value("${config.redisProjectName:''}")
  private String redisProjectName;

  @Bean
  public RedisTemplate<String, Object> redisTemplate(
      LettuceConnectionFactory redisConnectionFactory) {
    RedisTemplate<String, Object> template = new RedisTemplate<>();
    template.setKeySerializer(new StringRedisSerializer());
    template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
    template.setConnectionFactory(redisConnectionFactory);
    return template;
  }

  @Bean(name = "cacheManager")
  @Primary
  public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
    MyRedisCacheWriter cachaWriterCustomer = new MyRedisCacheWriter(redisConnectionFactory);
    RedisCacheConfiguration cacheConfiguration =
        RedisCacheConfiguration.defaultCacheConfig()
            // .entryTtl(Duration.ofSeconds(50))设置过期时间
            .disableCachingNullValues()
            .computePrefixWith(
                cacheName -> {
                  if (StringUtils.isEmpty(redisProjectName)) {
                    return cacheName.concat(":");
                  } else {
                    return redisProjectName.concat(":").concat(cacheName).concat(":");
                  }
                })
            .serializeKeysWith(
                RedisSerializationContext.SerializationPair.fromSerializer(
                    new StringRedisSerializer()))
            .serializeValuesWith(
                RedisSerializationContext.SerializationPair.fromSerializer(
                    new GenericJackson2JsonRedisSerializer()));
    return RedisCacheManager.builder(cachaWriterCustomer).cacheDefaults(cacheConfiguration).build();
  }
}
